//
//  iCloudManager.swift
//  LiLi
//
//  Created by liuzhu on 2019/1/8.
//  Copyright © 2019 liuzhu. All rights reserved.
//

import UIKit
import CloudKit
class iCloudManager: NSObject {
    var myContainer:CKContainer? = nil
    // 初始化
    static let iCloud: iCloudManager = {
        let c = iCloudManager()
        return c
    }()
    
    // 获取单例
    class func shareiCloudManager() -> iCloudManager {
        iCloud.myContainer = CKContainer(identifier: "iCloud.com.leisger.lilizaimu")
        return iCloud
    }
    
    //1.查询icloud上所有记录，同步到本地数据库(互相同步)
    func synciCloud(finish:@escaping(_ isSuccess:Bool)->()){
        let database = myContainer!.privateCloudDatabase
        syncAction(database: database) { (_isSuccess) in
            
        }
        syncRemark(database: database) { (isSuccess) in
            
        }
    }
    
    func syncAction(database:CKDatabase,finish:@escaping(_ isSuccess:Bool)->()){
        let predicate = NSPredicate(format: "isRemoved == 0")
        let query = CKQuery(recordType: "Action", predicate: predicate)
        database.perform(query, inZoneWith: nil) { (records, error) in
            if error == nil{
                if records?.count != 0{
                    for record in records!{
                        let icloudAction = LLAction()
                        icloudAction.recordName = record.recordID.recordName
                        let actionType = record.value(forKey: "actionType")
                        icloudAction.actionType = ActionType(rawValue: Int(truncating: actionType as! NSNumber))!
                        icloudAction.dateStr = (record.value(forKey: "dateStr") as! String)
                        icloudAction.subDateStr = (record.value(forKey: "subDateStr") as! String)
                        icloudAction.createTime = (record.value(forKey: "createTime") as! String)
                        icloudAction.updateTime = (record.value(forKey: "updateTime") as! String)
                        icloudAction.needTip = (record.value(forKey: "needTip") as! Int32)
                        icloudAction.refreshTag = (record.value(forKey: "refreshTag") as! Int32)
                        let repeatTag = record.value(forKey: "repeatTag")
                        icloudAction.repeatTag = ActionRepeatTag(rawValue: Int(truncating: repeatTag as! NSNumber))!
                        icloudAction.status = (record.value(forKey: "status") as! Int32)
                        icloudAction.timeStr = (record.value(forKey: "timeStr") as! String)
                        icloudAction.titleName = (record.value(forKey: "titleName") as! String)
                        icloudAction.des = (record.value(forKey: "des") as! String)
                        
                        let localAction = DataManager.QueryAction(recordName: icloudAction.recordName!)
                        if localAction == nil{
                            LLManager.shareLLManager().saveAction(action: icloudAction, finish: { (isSuccess) in
                                if isSuccess{
                                     NotificationCenter.default.post(name: NSNotification.Name(rawValue: LLActionAddKey), object: nil, userInfo: ["action":icloudAction])
                                }
                            })
                        }else{
                            if icloudAction.refreshTag! > (localAction?.refreshTag)!{
                                LLManager.shareLLManager().saveAction(action: icloudAction, finish: { (isSuccess) in
                                    NotificationCenter.default.post(name: NSNotification.Name(rawValue: LLActionUpdateKey), object: nil, userInfo: ["action":icloudAction])
                                })
                            }
                        }
                    }
                }
            }
        }
    }
    
    func syncRemark(database:CKDatabase,finish:@escaping(_ isSuccess:Bool)->()){
        let predicate = NSPredicate(format: "isRemoved == 0")
        let query = CKQuery(recordType: "Remark", predicate: predicate)
        database.perform(query, inZoneWith: nil) { (records, error) in
            if error == nil{
                if records?.count != 0{
                    for record in records!{
                        let icloudRemark = LLRemark()
                        icloudRemark.recordName = record.recordID.recordName
                        icloudRemark.actionId = (record.value(forKey: "actionId") as! String)
                        icloudRemark.imageId = (record.value(forKey: "imageId") as! String)
                        icloudRemark.createTime = (record.value(forKey: "createTime") as! String)
                        icloudRemark.refreshTag = (record.value(forKey: "refreshTag") as! Int32)
                        icloudRemark.titleName = (record.value(forKey: "titleName") as! String)
                        icloudRemark.des = (record.value(forKey: "des") as! String)
                        
                        let localRemark = DataManager.QueryRemark(recordName: icloudRemark.recordName!)
                        if localRemark == nil{
                            DataManager.saveRemark(remark: icloudRemark, finish: { (isSuccess) in
                                
                            })
                        }else{
                            
                        }
                    }
                }
            }
        }
    }
    
    //2.监听通知，一档Sqllite有更新，立刻同步到iCloud
    func uploadiCloud(recordType:String,model:AnyObject,notifiName:Notification.Name,finish:@escaping(_ isSuccess:Bool)->()){
        if(notifiName == NSNotification.Name(rawValue: LLActionAddKey)){
            let actionModel = model as! LLAction
            let recordId = CKRecord.ID(recordName: actionModel.recordName!)
            let record = CKRecord(recordType: recordType, recordID: recordId)
            record.setValue(Int(Float(actionModel.actionType.rawValue)), forKey: "actionType")
            record.setValue(actionModel.dateStr!, forKey: "dateStr")
            record.setValue(actionModel.subDateStr!, forKey: "subDateStr")
            record.setValue(actionModel.createTime!, forKey: "createTime")
            record.setValue(actionModel.updateTime!, forKey: "updateTime")
            record.setValue(actionModel.needTip!, forKey: "needTip")
            record.setValue(actionModel.refreshTag!, forKey: "refreshTag")
            record.setValue(Int(Float(actionModel.repeatTag.rawValue)), forKey: "repeatTag")
            record.setValue(actionModel.status!, forKey: "status")
            record.setValue(actionModel.timeStr!, forKey: "timeStr")
            record.setValue(actionModel.titleName!, forKey: "titleName")
            record.setValue(actionModel.des!, forKey: "des")
            record.setValue(0, forKey: "isRemoved")
            let database = myContainer!.privateCloudDatabase
            database.save(record) { record, error in
            
            }
        }else if(notifiName == NSNotification.Name(rawValue: LLRemarkAddKey)){
            let remarkModel = model as! LLRemark
            let recordId = CKRecord.ID(recordName: remarkModel.recordName!)
            let record = CKRecord(recordType: recordType, recordID: recordId)
            record.setValue(remarkModel.actionId, forKey: "actionId")
            record.setValue(remarkModel.createTime, forKey: "createTime")
            record.setValue(remarkModel.des, forKey: "des")
            record.setValue(remarkModel.imageId, forKey: "imageId")
            record.setValue(0, forKey: "isRemoved")
            record.setValue(remarkModel.refreshTag, forKey: "refreshTag")
            record.setValue(remarkModel.titleName, forKey: "titleName")
            let database = myContainer!.privateCloudDatabase
            database.save(record) { record, error in
                
            }
        }else if(notifiName == NSNotification.Name(rawValue: LLActionUpdateKey)){
            let actionModel = model as! LLAction
            let recordId = CKRecord.ID(recordName: actionModel.recordName!)
            let database = myContainer!.privateCloudDatabase
            database.fetch(withRecordID: recordId) { (record, error) in
                if (error != nil){
                    
                }else{
                    record!.setValue(Int(Float(actionModel.actionType.rawValue)), forKey: "actionType")
                    record!.setValue(actionModel.dateStr!, forKey: "dateStr")
                    record!.setValue(actionModel.subDateStr!, forKey: "subDateStr")
                    record!.setValue(actionModel.createTime!, forKey: "createTime")
                    record!.setValue(actionModel.updateTime!, forKey: "updateTime")
                    record!.setValue(actionModel.needTip!, forKey: "needTip")
                    record!.setValue(actionModel.refreshTag!, forKey: "refreshTag")
                    record!.setValue(Int(Float(actionModel.repeatTag.rawValue)), forKey: "repeatTag")
                    record!.setValue(actionModel.status!, forKey: "status")
                    record!.setValue(actionModel.timeStr!, forKey: "timeStr")
                    record!.setValue(actionModel.titleName!, forKey: "titleName")
                    record!.setValue(actionModel.des!, forKey: "des")
                    record!.setValue(0, forKey: "isRemoved")
                    database.save(record!, completionHandler: { (record, error) in
                        
                    })
                }
            }
        }else if(notifiName == NSNotification.Name(rawValue: LLActionDeleteKey)){
            let actionModel = model as! LLAction
            let recordId = CKRecord.ID(recordName: actionModel.recordName!)
            let database = myContainer!.privateCloudDatabase
            database.fetch(withRecordID: recordId) { (record, error) in
                if (error != nil){
                    
                }else{
                    record!.setValue(Int(Float(actionModel.actionType.rawValue)), forKey: "actionType")
                    record!.setValue(actionModel.dateStr!, forKey: "dateStr")
                    record!.setValue(actionModel.subDateStr!, forKey: "subDateStr")
                    record!.setValue(actionModel.createTime!, forKey: "createTime")
                    record!.setValue(actionModel.updateTime!, forKey: "updateTime")
                    record!.setValue(actionModel.needTip!, forKey: "needTip")
                    record!.setValue(actionModel.refreshTag!, forKey: "refreshTag")
                    record!.setValue(Int(Float(actionModel.repeatTag.rawValue)), forKey: "repeatTag")
                    record!.setValue(actionModel.status!, forKey: "status")
                    record!.setValue(actionModel.timeStr!, forKey: "timeStr")
                    record!.setValue(actionModel.titleName!, forKey: "titleName")
                    record!.setValue(actionModel.des!, forKey: "des")
                    record!.setValue(1, forKey: "isRemoved")
                    database.save(record!, completionHandler: { (record, error) in
                        
                    })
                }
            }
            
        }else if(notifiName == NSNotification.Name(rawValue: LLRemarkDeleteKey)){
            let remarkModel = model as! LLRemark
            let recordId = CKRecord.ID(recordName: remarkModel.recordName!)
            let database = myContainer!.privateCloudDatabase
            database.fetch(withRecordID: recordId) { (record, error) in
                if (error != nil){
                    
                }else{
                    record!.setValue(remarkModel.actionId, forKey: "actionId")
                    record!.setValue(remarkModel.createTime, forKey: "createTime")
                    record!.setValue(remarkModel.des, forKey: "des")
                    record!.setValue(remarkModel.imageId, forKey: "imageId")
                    record!.setValue(1, forKey: "isRemoved")
                    record!.setValue(remarkModel.refreshTag, forKey: "refreshTag")
                    record!.setValue(remarkModel.titleName, forKey: "titleName")
                    database.save(record!, completionHandler: { (record, error) in
                        
                    })
                }
            }
        }
    }
}
